<template>
    <el-form ref="formRef" :model="form" label-width="120px">
        <el-form-item prop="name" label="分类名称" style="width: 92%">
            <el-input v-model="form.name" placeholder="请填写分类名称" />
        </el-form-item>

        <el-form-item label="分类级别">
            <el-radio-group v-model="showMore">
                <el-radio :label="false">一级分类</el-radio>
                <el-radio :label="true">二级分类</el-radio>
            </el-radio-group>
        </el-form-item>

        <el-form-item v-show="showMore" label="上级分类" prop="pid" style="width: 50%">
            <el-select v-model="form.pid" placeholder="请选择上级分类名称">
                <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
        </el-form-item>

        <el-form-item label="分类图片" v-show="showMore">
            <el-upload ref="uploadRef" class="upload-demo" v-model:file-list="fileList" :on-exceed="handleExceed"
                :on-success="uploadSuccess" :limit="1" :action="uploadPictureURL()"
                :headers="{ jwt: token }" :data="{ type: 'category_picture' }">
                <template #trigger>
                    <el-button type="primary">请选择图片</el-button>
                </template>
                <template #tip>
                    <div class="el-upload__tip">
                        图片文件大小不超过500KB
                    </div>
                </template>
            </el-upload>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="editSubmit" v-if="id">修改</el-button>
            <el-button type="primary" @click="addSubmit" v-else>新增</el-button>
            <el-button @click="btnCancel">重置</el-button>
        </el-form-item>
    </el-form>
</template>
<script setup>
import { UploadFilled } from '@element-plus/icons-vue'
import { ref, reactive, onMounted, watch } from 'vue'
import { addCategory, getCategoryList, getCategory, editCategory,uploadPictureURL } from '../api/api'
import useToken from '../store/token'
import notification from '../utils/notification'
const uploadRef = ref()
var fileList = ref([])
const handleExceed = (files) => {
    uploadRef.value.clearFiles()
    fileList.value = [files[0]]
    uploadRef.value.handleStart(files[0])
    uploadRef.value.submit()
}
const { token } = useToken()

const props = defineProps({
    id: {
        type: Number,
    },
});
const emit = defineEmits(["success"]);
const form = reactive({
    id: props.id,
    name: "",
    picture: "",
    pid: "",
});
const formRef = ref();
const categoryList = ref([]);
const showMore = ref(false);
onMounted(() => {
    loadCategory();
})
const btnCancel = () => {
    formRef.value.resetFields();
    form.picture = "";
    uploadRef.value.clearFiles();
    loadCategory();
};
const resetForm = (id) => {
    form.id = id;
    btnCancel();
};
const loadCategory = async () => {
    if (form.id) {
        const data = await getCategory({ id: form.id });
        if (data.picture !== "") {
            const fileName = data.picture.substring(
                data.picture.lastIndexOf("/") + 1
            );
            if (fileName) {
                fileList.value = [{ name: fileName, url: data.picture }];
            }
        }
        Object.assign(form, data);
    }
    const list = await getCategoryList();
    categoryList.value = list.filter((item) => item.pid == 0);
    showMore.value = form.pid != 0
}
const addSubmit = async () => {
    if (!form.name) {
        notification({
            message: '请填写分类名称',
            type: 'warning'
        })
        return
    }

    if (showMore.value && !form.picture && fileList.value.length === 0) {
        notification({
            message: '请上传分类图片',
            type: 'warning'
        })
        return
    }
    
    const data = {
        name: form.name,
        picture: form.picture,
        pid: showMore.value ? (form.pid || 0) : 0
    }
    console.log('提交的数据：', data)
    if (await addCategory(data)) {
        emit("success")
    }
}
const editSubmit = async () => {
    if (!form.name) {
        notification({
            message: '请填写分类名称',
            type: 'warning'
        })
        return
    }

    if (showMore.value && !form.picture && fileList.value.length === 0) {
        notification({
            message: '请上传分类图片',
            type: 'warning'
        })
        return
    }
    
    const data = {
        id: form.id,
        name: form.name,
        picture: form.picture,
        pid: showMore.value ? (form.pid || 0) : 0
    }
    if (await editCategory(data)) {
        emit("success")
    }
}
defineExpose({ resetForm });
const uploadSuccess = (response) => {
    
    // 处理XML格式的响应
    let errno, errmsg, data
    
    if (typeof response === 'string' && response.includes('APIResponse')) {
        // 解析XML字符串
        const parser = new DOMParser()
        const xmlDoc = parser.parseFromString(response, 'text/xml')
        
        errno = parseInt(xmlDoc.querySelector('errno')?.textContent || '-1')
        errmsg = xmlDoc.querySelector('errmsg')?.textContent || ''
        data = xmlDoc.querySelector('data')?.textContent || ''
    } else {
        // 如果不是XML格式，尝试正常解构
        ({ errno, errmsg, data } = response)
    }
    
    if (errno !== 0) {
        notification({
            message: errmsg || '上传失败',
            type: 'error'
        })
        return
    }
    
    // 设置完整的图片URL路径
    form.picture = data
    
    // 更新文件列表显示
    if (data) {
        const fileName = data.substring(data.lastIndexOf("/") + 1)
        fileList.value = [{
            name: fileName,
            url: data
        }]
    }
}

watch(fileList, (newVal) => {
    console.log('fileList changed:', newVal)
    if (newVal && newVal.length > 0) {
        // 如果有url就使用url，否则使用raw文件名
        form.picture = newVal[0].url || newVal[0].name
        console.log('从fileList更新picture:', form.picture)
    } else {
        form.picture = ''
    }
}, { deep: true })
</script>